package com.ruoyi.ly.controller;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/myws/{userId}")
@Component
public class WsServerEndpont {
    // 定义一个全局的集合，保存所有的在线用户对象，便于为指定用户发送消息
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId){
        sessionMap.put(userId,session);
        System.out.println("客户端登录了"+ userId);
    }
    @OnMessage
    public String onMessage(String mess,@PathParam("userId") String userId)
            throws IOException {
        System.out.println("接收到" + userId + "发送的一条消息：" + mess);
        for (String key : sessionMap.keySet()) {
            sessionMap.get(key).getBasicRemote().sendText(userId + ":" + mess);
        }
        return "已收到消息";
    }
    @OnClose
    public void onClose(@PathParam("userId") String userId){
        sessionMap.remove(userId);
        System.out.println("一个账号退出了"+userId);
    }
}
